<style>
.pure_form_extra .mandatory { color: #ff0000; padding-left: 5px; }
.pure_table_extra { width: 900px; margin-top: 5px; }
.pure_table_extra th { height: 25px; line-height: 25px; }
.pure_table_extra td { vertical-align: middle; }
.pure_table_extra select { width: 100%; }
.chosen-choices input { height: 25px !important; width: 100% !important; }
.chosen-container { display: inline-block; width: 400px !important; }
</style>

<?php 
$PT = PT_DIPLOMA;

$id = Utils::get_param('id', -1);
$opts = new stdClass();
$opts->cd = 't.id = :v1';
$opts->cdv = array(':v1' => $id);
$intakes = $orm->get('pb_colg_intake', NULL, NULL, NULL, NULL, $opts)->d;

$pg = Utils::get_param('pg', 1);
$opts = new stdClass();
$opts->cd = 't.type = :v1';
$opts->cdv = array(':v1' => PT_DIPLOMA);
$objs = $orm->get('pb_colg_intake', 't.start', 'DESC', $pg, SIZE, $opts);

$opts = new stdClass();
$opts->cd = 't.intake_id = :v1';
$opts->cdv = array(':v1' => $id);
$data = $orm->get('pb_colg_class', 't.course_name', 'ASC', NULL, NULL, $opts)->d;
foreach ($data as $itm) {
  $itm->times = json_decode($itm->times);
}
$teachers = $orm->get('pb_colg_teacher', 't.first_name', 'ASC', NULL, NULL, NULL)->d;
$classrooms = $orm->get('pb_colg_classroom', 't.name', 'ASC', NULL, NULL, NULL)->d;
$courses = $orm->get('pb_colg_course', 't.code', 'ASC', NULL, NULL, NULL)->d;

$opts = new stdClass();
$opts->cd = 't.type = :v1';
$opts->cdv = array(':v1' => PT_DIPLOMA);
$programs = $orm->get('pb_colg_program', 't.name', 'ASC', NULL, NULL, $opts)->d;
?>
<div class="pure-form pure-form-aligned pure_form_extra" style="padding: 10px; width: 580px;">
  <legend>Intake</legend>

  <div class="pure-control-group">
    <label>Start<span class="mandatory">*</span></label>
    <input id="start" type="text" class="pure-input-1-2" placeholder="{Start Date}" />
  </div>
  
  <div class="pure-control-group">
    <label>End<span class="mandatory">*</span></label>
    <input id="end" type="text" class="pure-input-1-2" placeholder="{End Date}" />
  </div>
  
  <div class="pure-control-group">
    <label>Programs<span class="mandatory">*</span></label>
    <span id="programs"></span>
  </div>
        
  <div class="pure-control-group">
    <label>&nbsp;</label>
    <button class="pure-button pure-input-1-2 pure-button-primary" onclick="submit_obj();">Save</button>
  </div>
  
  <div class="pure-control-group expg">
    <label>&nbsp;</label>
    <button class="pure-button" onclick="delete_obj();">Delete</button>
    <button class="pure-button" onclick="__intakes = []; __data = []; reset(); render();">New Intake</button>
  </div>
</div>

<div class="expg">
  <div class="pure-form">
    <select style="width: 240px;" id="new_course"><option value="0">Choose a course...</option></select>
    <input style="width: 100px;" id="new_name" type="text" placeholder="{Class Name}" onkeypress="if(event.which == 13) add_obj();" />
    <select style="width: 160px;" id="new_teacher"><option value="0">Choose a teacher...</option></select>
    <select style="width: 160px;" id="new_classroom"><option value="0">Choose a classroom...</option></select>
    <button type="submit" class="pure-button pure-button-primary" onclick="add_obj();">Add</button>
  </div>
  <table class="pure-table pure_table_extra" cellpadding=0 cellspacing=0>
    <thead>
      <tr>
        <th class="ui-widget-header" style="width: 200px;">Course</th>
        <th class="ui-widget-header" style="width: 100px;">Name</th>
        <th class="ui-widget-header" style="width: 120px;">Teacher</th>
        <th class="ui-widget-header" style="width: 120px;">Classroom</th>
        <th class="ui-widget-header">Time</th>
        <th class="ui-widget-header" style="width: 40px;">&nbsp;</th>
      </tr>
    </thead>
    <tbody id="data_body"></tbody>
  </table>
  <div>&nbsp;</div>
  <div id="timetable"></div>
  
  <div id="dialog_change" class="pure-form" style="display: none;" title="Change Name">
    <input type="text" id="name_change" style="width: 100%;"></input>
  </div>
  
  <div id="dialog_tt" class="pure-form" style="display: none;">
    <div id="class_tt"></div>
    <input type="text" id="start_tt" />&nbsp;<input type="text" id="end_tt" />
  </div>
</div>

<script type="text/javascript">
  /*<![CDATA[*/
  var __teachers = JSON.parse('<?php echo addslashes(json_encode($teachers)); ?>');
  var __classrooms = JSON.parse('<?php echo addslashes(json_encode($classrooms)); ?>');
  var __courses = JSON.parse('<?php echo addslashes(json_encode($courses)); ?>');
  var __data = JSON.parse('<?php echo addslashes(json_encode($data)); ?>');
  var __objs = JSON.parse('<?php echo addslashes(json_encode($objs)); ?>');
  var __intakes = JSON.parse('<?php echo addslashes(json_encode($intakes)); ?>');
  var __programs = JSON.parse('<?php echo addslashes(json_encode($programs)); ?>');
  var __dir = '<?php echo PLGN_DIR . basename(dirname(__FILE__)); ?>';
  var __requrl = '<?php echo Utils::get_requrl($app_data); ?>';
  var __file = '<?php echo addslashes($app_data->param_file); ?>';
  var __redmd = '<?php echo addslashes($app_data->sys->redmd); ?>';
  var __sys = '<?php echo addslashes($app_data->sys->php_name); ?>';
  var __id = '<?php echo $app_data->param_id; ?>';
  var __type = '<?php echo $PT; ?>';
  
  $(function() {
    reset();
    
    $('#start').datepicker({
      changeMonth: true,
      changeYear: true,
      dateFormat: "yy-mm-dd",
      showButtonPanel: true
    });
    $('#end').datepicker({
      changeMonth: true,
      changeYear: true,
      dateFormat: "yy-mm-dd",
      showButtonPanel: true
    });

    for (var idx in __courses) {
      var itm = __courses[idx];
      $('#new_course').append('<option value="' + itm.id + '">' + itm.title__ + '</option>');
    }
    for (var idx in __teachers) {
      var itm = __teachers[idx];
      $('#new_teacher').append('<option value="' + itm.id + '">' + itm.first_name + ' ' + itm.last_name + '</option>');
    }
    for (var idx in __classrooms) {
      var itm = __classrooms[idx];
      $('#new_classroom').append('<option value="' + itm.id + '">' + itm.name + '</option>');
    }
    
    render();
  });
  
  function reset() {
    if (__intakes.length == 0) {
      __intakes[0] = {
        id: -1,
        type: __type,
        start: '',
        end: '',
        title__: '',
        programs__: ''
      };
    }
    __data = __data.sort(function(a, b) {
      return a.course_name.localeCompare(b.course_name);
    });
  };

  function render() {
    if (__intakes[0].id != -1) {
      $('.expg').show();
    } else {
      $('.expg').hide();
    }
    Utils.leftbar(
      __objs,
      __intakes[0].id,
      'Diploma Intakes',
      'title__',
      function(page) {
        Url.redirect(__redmd, __sys + '.php?i=' + __id + '&__file=' + __file + '&id=' + __intakes[0].id + '&pg=' + page);
      }
    );
    render_intakes();
    $('#new_name').val('');
    $('#new_teacher').val(0);
    $('#new_classroom').val(0);
    
    $('#timetable').empty();
    $('#timetable').fullCalendar({
      defaultView: 'agendaWeek',
      header: {
        left: '',
        center: '',
        right: ''
      },
      columnFormat: {
        week: 'ddd'
      },
      year: 2000,
      month: 0,
      date: 3,
      allDaySlot: false,
      height: 800,
      weekends: true,
      theme: true,
      
      minTime: 9,
      maxTime: 23,
      
      timeFormat: 'HH:mm{-HH:mm}',

      editable: true,
      selectable: true,

      eventDrop: function(event, dayDelta, minuteDelta, allDay, revertFunc) {
        event.__obj.times[event.__idx] = $.fullCalendar.formatDate(event.start, 'yyyy-MM-dd HH:mm') + '#' + $.fullCalendar.formatDate(event.end, 'yyyy-MM-dd HH:mm');
        Ajax.request(
          __requrl + 'submit_class',
          'req=' + Utils.encodeURI(JSON.stringify(event.__obj)),
          function(rslt) {
            render_data();
          },
          null
        );
      },

      eventResize: function(event, dayDelta, minuteDelta, revertFunc, jsEvent, ui, view) {
        event.__obj.times[event.__idx] = $.fullCalendar.formatDate(event.start, 'yyyy-MM-dd HH:mm') + '#' + $.fullCalendar.formatDate(event.end, 'yyyy-MM-dd HH:mm');
        Ajax.request(
          __requrl + 'submit_class',
          'req=' + Utils.encodeURI(JSON.stringify(event.__obj)),
          function(rslt) {
            render_data();
          },
          null
        );
      },

      eventClick: function(event, jsEvent, view) {
        change_time(event.__obj.id, event.__idx, jsEvent, null, null);
      },

      select: function(start, end, allDay) {
        change_time(0, -1, null, $.fullCalendar.formatDate(start, 'yyyy-MM-dd HH:mm'), $.fullCalendar.formatDate(end, 'yyyy-MM-dd HH:mm'));
      },

      events: function(start, end, callback) {
        for(var idx in __data) {
          var itm = __data[idx];
          for (var idx2 in itm.times) {
            var itm2 = itm.times[idx2];
            var rslt = itm2.split('#');
            var evt = {
              __obj: itm,
              __idx: idx2,
              start: rslt[0] + ':00',
              end: rslt[1] + ':00',
              allDay: 0,
              title: itm.course_name + ' ' + itm.name + ((itm.room_id == 0) ? '' : '\n' + itm.room_name) + ((itm.teacher_id == 0) ? '' : '\n' + itm.teacher_name),
              description: ''
            };
            $("#timetable").fullCalendar('renderEvent', evt, true);
          }
        }
      }
    });
    render_data();
  };
  
  function render_data() {
    $('#data_body').empty();
    for (var idx in __data) {
      var itm = __data[idx];
      $('#data_body').append(
        '<tr class="' + ((idx % 2 == 0) ? 'pure-table-even' : 'pure-table-odd') + '">' + 
          '<td><select id="course_' + itm.id + '" onchange="update_course(' + itm.id + ', this);"><option value="0">&nbsp;</option></select></td>' +
          '<td><a href="#" onclick="change_name(' + itm.id + ', event);">' + ((itm.name != '') ? itm.name : '{None}') + '</a></td>' +
          '<td><select id="teacher_' + itm.id + '" onchange="update_teacher(' + itm.id + ', this);"><option value="0">&nbsp;</option></select></td>' +
          '<td><select id="classroom_' + itm.id + '" onchange="update_classroom(' + itm.id + ', this);"><option value="0">&nbsp;</option></select></td>' +
          '<td>' + get_times(itm.times) + '</td>' +
          '<td>' +
            '<span style="cursor: pointer; float: left;" class="ui-button-icon-primary ui-icon ui-icon-closethick" onclick="delete_class(' + itm.id + ');"></span>' +
          '</td>' + 
        '</tr>'
      );
      for (var idx2 in __courses) {
        var itm2 = __courses[idx2];
        $('#course_' + itm.id).append('<option value="' + itm2.id + '"' + ((itm2.id == itm.course_id) ? 'selected="selected"' : '') + '>' + itm2.title__ + '</option>');
      }
      for (var idx2 in __teachers) {
        var itm2 = __teachers[idx2];
        $('#teacher_' + itm.id).append('<option value="' + itm2.id + '"' + ((itm2.id == itm.teacher_id) ? 'selected="selected"' : '') + '>' + itm2.first_name + ' ' + itm2.last_name + '</option>');
      }
      for (var idx2 in __classrooms) {
        var itm2 = __classrooms[idx2];
        $('#classroom_' + itm.id).append('<option value="' + itm2.id + '"' + ((itm2.id == itm.room_id) ? 'selected="selected"' : '') + '>' + itm2.name + '</option>');
      }
    }
    if (__data.length == 0) {
      $('#data_body').append('<tr class="pure-table-even"><td colspan=6>None</td></tr>');
    }
  };

  function get_times(times) {
    var str = '';
    for (var idx in times) {
      var itm = times[idx];
      var rslt = itm.split('#');
      var ds = rslt[0].split(' ')[0].split('-');
      var d = new Date(ds[0], ds[1] - 1, ds[2]);
      str += ((str == '') ? '' : ', ');
      str += Utils.get_weekday(d.getDay()) + ' ' + rslt[0].split(' ')[1] + '-' + rslt[1].split(' ')[1];
    }
    return str;
  };
  
  function delete_class(id) {
    var req = Utils.get_by_id(id, __data);
    Ajax.request(
      __requrl + 'delete_class',
      'req=' + Utils.encodeURI(JSON.stringify(req)),
      function(rslt) {
        Utils.splice_by_id(id, __data);
        reset();
        render();
      },
      { confirm: 1 }
    );
  };

  function update_course(id, elm) {
    var req = Utils.get_by_id(id, __data);
    req.course_id = elm.options[elm.selectedIndex].value;
    req.course_name = elm.options[elm.selectedIndex].text;
    
    Ajax.request(
      __requrl + 'submit_class',
      'req=' + Utils.encodeURI(JSON.stringify(req)),
      function(rslt) {
        reset();
        render();
      },
      null
    );
  };
  
  function update_teacher(id, elm) {
    var req = Utils.get_by_id(id, __data);
    req.teacher_id = elm.options[elm.selectedIndex].value;
    req.teacher_name = elm.options[elm.selectedIndex].text;
    if (req.teacher_id == 0) {
      req.teacher_name = '';
    }
    Ajax.request(
      __requrl + 'submit_class',
      'req=' + Utils.encodeURI(JSON.stringify(req)),
      function(rslt) {
        reset();
        render();
      },
      null
    );
  };

  function update_classroom(id, elm) {
    var req = Utils.get_by_id(id, __data);
    req.room_id = elm.options[elm.selectedIndex].value;
    req.room_name = elm.options[elm.selectedIndex].text;
    if (req.room_id == 0) {
      req.room_name = '';
    }
    Ajax.request(
      __requrl + 'submit_class',
      'req=' + Utils.encodeURI(JSON.stringify(req)),
      function(rslt) {
        reset();
        render();
      },
      null
    );
  };

  function add_obj() {
    var req = {
      type: __type,
      name: $('#new_name').val(),
      course_id: $('#new_course option:selected').val(),
      course_name: $('#new_course option:selected').text(),
      intake_id: __intakes[0].id,
      teacher_id: $('#new_teacher option:selected').val(),
      teacher_name: $('#new_teacher option:selected').text(),
      room_id: $('#new_classroom option:selected').val(),
      room_name: $('#new_classroom option:selected').text(),
      times: [ '2000-01-03 09:00#2000-01-03 11:00', '2000-01-03 11:00#2000-01-03 13:00' ]
    };
    if (req.room_id == 0) {
      req.room_name = '';
    }
    if (req.teacher_id == 0) {
      req.teacher_name = '';
    }
    Ajax.request(
      __requrl + 'submit_class',
      'req=' + Utils.encodeURI(JSON.stringify(req)),
      function(rslt) {
        __data[__data.length] = rslt;
        reset();
        render();
      },
      null
    );
  };

  function change_name(id, ev) {
    var func = function() {
      var req = Utils.get_by_id(id, __data);
      req.name = $('#name_change')[0].value;
      Ajax.request(
        __requrl + 'submit_class',
        'req=' + Utils.encodeURI(JSON.stringify(req)),
        function(rslt) {
          reset();
          render();
          $('#dialog_change').dialog('close');
        },
        null
      );
    };
    
    $('#dialog_change').dialog({
      position: {
        my: 'left+0 bottom+0',
        of: ev.target
      },
      buttons: {
        'OK': function() {
          func();
        },
        'Cancel': function() { 
          $(this).dialog('close');
        }
      }
    });

    var obj = Utils.get_by_id(id, __data);
    
    $('#name_change')[0].onkeypress = function(ev) {
      if(ev.which == 13) {
        func();
      }
    };
    $('#name_change').val(obj.name);
    $('#name_change').select();
  };

  function change_time(id, index, ev, start, end) {
    var func = function() {
      if (id == 0) {
        id = $('#newclass_tt option:selected').val();
      }
      var req = Utils.get_by_id(id, __data);
      if (index == -1) {
        req.times[req.times.length] = start.split(' ')[0] + ' ' + $('#start_tt').val() + '#' + end.split(' ')[0] + ' ' + $('#end_tt').val();
      } else {
        req.times[index] = rslt[0].split(' ')[0] + ' ' + $('#start_tt').val() + '#' + rslt[0].split(' ')[0] + ' ' + $('#end_tt').val();
      }
      Ajax.request(
        __requrl + 'submit_class',
        'req=' + Utils.encodeURI(JSON.stringify(req)),
        function(rslt) {
          reset();
          render();
          $('#dialog_tt').dialog('close');
        },
        null
      );
    };
    
    $('#dialog_tt').dialog({
      position: {
        my: 'left+0 bottom+0',
        of: ev ? ev.target : $('#timetable')
      },
      buttons: {
        'OK': function() {
          func();
        },
        'Cancel': function() { 
          $(this).dialog('close');
        }
      }
    });
    
    if (id == 0) {
      $('#start_tt').val(start.split(' ')[1]);
      $('#end_tt').val(end.split(' ')[1]);
      $('#class_tt').html('<select id="newclass_tt"></select><div>&nbsp;</div>');
      for (var idx in __data) {
        var itm = __data[idx];
        $('#newclass_tt').append('<option value="' + itm.id + '">' + itm.course_name + ' ' + itm.name + '</option>');
      }
    } else {
      $('#dialog_tt').dialog('option', 'buttons', {
        'OK': function() {
          func();
        },
        'Delete': function() {
          var req = Utils.get_by_id(id, __data);
          req.times.splice(index, 1);
          Ajax.request(
            __requrl + 'submit_class',
            'req=' + Utils.encodeURI(JSON.stringify(req)),
            function(rslt) {
              reset();
              render();
              $('#dialog_tt').dialog('close');
            },
            null
          );
        },
        'Cancel': function() { 
          $(this).dialog('close');
        }
      });
      
      var obj = Utils.get_by_id(id, __data);
      var rslt = obj.times[index].split('#');
      $('#start_tt').val(rslt[0].split(' ')[1]);
      $('#end_tt').val(rslt[1].split(' ')[1]);
      $('#class_tt').html('<h3>' + obj.course_name + ' ' + obj.name + '</h3>');
    }
    $('#start_tt').timepicker({ 'step': 5, 'timeFormat': 'H:i', 'scrollDefaultTime': true });
    $('#end_tt').timepicker({ 'step': 5, 'timeFormat': 'H:i', 'scrollDefaultTime': true });
  };
  
  function render_intakes() {
    Url.insert_param('id', __intakes[0].id);
    $('#start').val(__intakes[0].start);
    $('#end').val(__intakes[0].end);

    $('#programs').empty();
    $('#programs').html('<select multiple></select>');
    for (var idx in __programs) {
      var itm = __programs[idx];
      $('#programs select').append('<option' + ((__intakes[0].programs__.indexOf(',' + itm.id + ',') != -1) ? ' selected="selected"' : '') +  ' value="' + itm.id + '">' + itm.name + '</option>');
    }
    $('#programs select').chosen();
  };

  function submit_obj() {
    req = __intakes[0];
    req.start = $('#start').val();
    req.end = $('#end').val();
    req.title__ = req.start + ' to ' + req.end;
    req.__pg = __objs.p;

    var ps = $('#programs select').val();
    if (!ps) {
      req.programs__ = '';
    } else {
      req.programs__ = ',' + ps.join(',') + ',';
    }
    
    Ajax.request(
      __requrl + 'submit_obj',
      'req=' + Utils.encodeURI(JSON.stringify(req)),
      function(rslt) {
        if (rslt.__objs) {
          __objs = rslt.__objs;
          delete rslt.__objs;
        }
        __intakes[0] = rslt;
        render();
      },
      null
    );
  };
  
  function delete_obj() {
    Ajax.request(
      __requrl.replace(__file, 'index') + 'delete_obj',
      'req=' + Utils.encodeURI(JSON.stringify(__intakes[0])),
      function(rslt) {
        Url.redirect(__redmd, __sys + '.php?i=' + __id);
      },
      { confirm: 1 }
    );
  };

  function get_obj(id) {
    var req = {
      id: id
    };
    Ajax.request(
      __requrl + 'get_obj',
      'req=' + Utils.encodeURI(JSON.stringify(req)),
      function(rslt) {
        __data = rslt.__data;
        delete rslt.__data;
        __intakes = rslt;
        render();
      },
      null
    );
    return false;
  };
  /*]]>*/
</script>